const appConfig = require('../../config/config.js');
const http = require('../../utils/http.js');
const nav = require('../../utils/navigator.js');
const util = require('../../utils/util.js');
const tip = require('../../utils/tip.js');
// 引入SDK核心类
var QQMapWX = require('../../libs/qqmap-wx-jssdk.js');

//index.js
//获取应用实例
const app = getApp()

Page({

  data: {
    //底部导航栏配置
    //定义一个数组，数组每一项是对象，对象里面对应菜单的数据
    //管理菜单的每一项的不同参数，还有不同布局结构需要的额外的参数
    navData: [{
      name: "寻宠", //文本
      current: 1, //是否是当前页，0不是  1是
      style: 0, //样式
      ico: 'icon-zhonglixunta', //不同图标
      fn: 'gotoNoticeIndex' //对应处理函数
    }, {
      name: "寻主人",
      current: 0,
      style: 0,
      ico: 'icon-xunren',
      fn: 'gotoPickupIndex'
    }, {
      name: "",
      current: 0,
      style: 1,
      ico: '',
      fn: 'gotopublish'
    }, {
      name: "圈子",
      current: 0,
      style: 0,
      ico: 'icon-qz',
      fn: 'gotoQuanzi',
    }, {
      name: "我的",
      current: 0,
      style: 0,
      ico: 'icon-wode2',
      fn: 'bindViewMy'
    }],
    noticeType: 0, //默认为寻TA启事
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    hiddenModal: true,
    pageIndex: {}, //当前页码
    pageData: {}, //分页数据
    loadMoreText: '正在载入更多...', //上拉加载提示文本
    hideBottom: true, //上拉加载提示层
    currentAddress: {}, //当前定位地址
    currentArea: '',
    currentPz: '品种',
    qyopen: false,
    qyshow: true,
    nzopen: false,
    pxopen: false,
    nzshow: true,
    pxshow: true,
    provice: {}, //省列表
    city: {}, //城市列表
    region: {}, //行政区列表
    //address: {}, //行政区下属区域列表
    categoryParentList: {}, //品种-父类
    categoryParentChildList: {}, //品种-子类
    selected_categoryParent: -1, //
    selected_categoryChild: {}, //
    selected_provice: {},
    selected_city: {},
    selected_region: {},
    pname: '',
    cname: '',
    //selected_address: {},
    selected_publishTime: '',
    selected_status: '',
    selected_gender: -1,
    selected_color: -1,
    shownavindex: ''
  },

  onReady: function () {

  },
  onLoad: function (options) {

    var that = this;
    console.log(wx.getStorageSync('userId'));
    if (wx.getStorageSync('userId') == [] || wx.getStorageSync('userId') == 0) {
      wx.redirectTo({
        url: '/pages/authorize/authorize'
      });
    } else {
      var cur0 = "navData[0].current";
      var cur1 = "navData[1].current";
      if (options.noticeType == null) {
        that.setData({
          noticeType: 0
        })
      } else
      if (options.noticeType == 0) {
        //wx.setNavigationBarTitle({title: '寻宠' });
        that.setData({
          [cur0]: 1,
          [cur1]: 0,
          noticeType: options.noticeType
        })
      } else {
        //wx.setNavigationBarTitle({ title: '寻主人'});
        that.setData({
          [cur0]: 0,
          [cur1]: 1,
          noticeType: options.noticeType
        })
      }

      that.setData({
        selected_categoryChild: options.selected_categoryChild == null ? {} : options.selected_categoryChild,
        currentPz: options.currentPz == null ? '品种' : options.currentPz
      });
      console.log(that.data.selected_categoryChild)

      var qqMap = new QQMapWX({
        key: appConfig.QQMapWXKey // 必填
      });
      if (app.globalData.userInfo) {
        this.setData({
          userInfo: app.globalData.userInfo,
          hasUserInfo: true
        })
      } else if (this.data.canIUse) {
        // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
        // 所以此处加入 callback 以防止这种情况
        app.userInfoReadyCallback = res => {
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      } else {
        // 在没有 open-type=getUserInfo 版本的兼容处理
        wx.getUserInfo({
          success: res => {
            app.globalData.userInfo = res.userInfo
            this.setData({
              userInfo: res.userInfo,
              hasUserInfo: true
            })
          }
        })
      };
      wx.showLoading({
        title: '玩命加载中...',
      });
      //获取地理位置

      app.getLocationInfo(function (data) {
        // 调用腾讯地图的接口查询当前位置
        qqMap.reverseGeocoder({
          location: {
            latitude: data.latitude,
            longitude: data.longitude
          },
          success: function (res) {
            console.log(res)

            that.setData({
              currentAddress: res.result.address_component.province + "-" + res.result.address_component.city + "-" + res.result.address_component.district,
              currentArea: res.result.address_component.district,
              pname: res.result.address_component.province,
              cname: res.result.address_component.city
            });
            //获取数据更新页面
            console.log(res.result.address);

            http.post(appConfig.baseUrl + 'Login/UpdateLocation', {
              Id: wx.getStorageSync('userId'),
              Latitude: data.latitude,
              Longitude: data.longitude
            }, function (ret) {
              console.log(ret.data);
            });
            console.log(res.result)
            //加载列表
            http.post(appConfig.baseUrl + 'Notice/GetCurrentRegion', {

                ProviceName: res.result.address_component.province,
                CityName: res.result.address_component.city,
                AreaName: res.result.address_component.district
              },
              function (res) { //
                console.log(res.data)
                if (res.data.Flag) {
                  that.setData({
                    selected_provice: res.data.Content.split(",")[0],
                    selected_city: res.data.Content.split(",")[1],
                    selected_region: res.data.Content.split(",")[2]
                  });
                  //加载省列表
                  http.post(
                    appConfig.baseUrl + 'Notice/GetRegionByParentId', {
                      ParentId: 1
                    },
                    function (res) {
                      that.setData({
                        provice: res.data
                      })
                    });
                  //加载市列表
                  http.post(
                    appConfig.baseUrl + 'Notice/GetRegionByParentId', {
                      ParentId: res.data.Content.split(",")[0]
                    },
                    function (res) {
                      that.setData({
                        city: res.data
                      })
                    });
                  //加载区列表
                  http.post(
                    appConfig.baseUrl + 'Notice/GetRegionByParentId', {
                      ParentId: res.data.Content.split(",")[1]
                    },
                    function (res) {
                      that.setData({
                        region: res.data
                      })
                    });
                  //加载区列表

                  http.post(appConfig.baseUrl + 'Notice/QueryNoticeList', {
                      PageIndex: 1,
                      ProviceId: that.data.selected_provice,
                      CityId: that.data.selected_city,
                      AreaId: that.data.selected_region,
                      CategoryId: that.data.selected_categoryChild,
                      NoticeType: that.data.noticeType,

                    },
                    function (res) { //
                      console.log(res.data);
                      var result = that.calculateDistance(res.data);
                      wx.hideLoading(); //关闭加载动画
                      that.setData({
                        pageIndex: 1, //当前页码
                        pageData: res.data, //分页数据
                        hideBottom: true,
                        loadMoreText: '正在载入更多...'
                      });

                    });
                }
              });

          },
          fail: function (res) {
            console.log(res);
          },
          complete: function (res) {
            // console.log(res);
          }
        });
      });
    }
  }, //onload end
  //列表点击事件
  item_click: function (e) {
    console.log(e.currentTarget.dataset.noticeId);
    nav.navigateTo('../detail/detail', {
      noticeId: e.currentTarget.dataset.noticeId
    });
  },
  getUserInfo: function (e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  // 下拉刷新
  onPullDownRefresh: function (e) {
    var that = this;
    // 显示顶部刷新图标
    wx.showNavigationBarLoading();

    http.post(appConfig.baseUrl + 'Notice/QueryNoticeList', {
        PageIndex: 1,
        NoticeType: that.data.noticeType,
        ProviceId: that.data.selected_provice,
        CityId: that.data.selected_city,
        AreaId: that.data.selected_region,
        //RegionId: that.data.selected_address,
        Gender: that.data.selected_gender,
        CategoryId: that.data.selected_categoryChild,
        Color: that.data.selected_color
      },
      function (res) { //
        console.log(res.data);
        var result = that.calculateDistance(res.data);
        that.setData({
          pageIndex: 1, //当前页码
          pageData: res.data, //分页数据
          hideBottom: true,
          loadMoreText: '正在载入更多...'
        });
        // 隐藏导航栏加载框
        wx.hideNavigationBarLoading();
        // 停止下拉动作
        wx.stopPullDownRefresh();
      });

  },
  //上拉加载
  onReachBottom: function (e) {
    var that = this;
    // 页数+1
    that.setData({
      pageIndex: that.data.pageIndex + 1,
      hideBottom: false
    });

    console.log(that.data.pageIndex);
    http.post(appConfig.baseUrl + 'Notice/QueryNoticeList', {
        PageIndex: that.data.pageIndex,
        NoticeType: that.data.noticeType,
        ProviceId: that.data.selected_provice,
        CityId: that.data.selected_city,
        AreaId: that.data.selected_region,
        //RegionId: that.data.selected_address,
        Gender: that.data.selected_gender,
        CategoryId: that.data.selected_categoryChild,
        Color: that.data.selected_color
      },
      function (res) { //
        console.log(res.data);
        var result = that.calculateDistance(res.data);
        if (res.data.length > 0) {
          var data_list = that.data.pageData;
          for (var i = 0; i < res.data.length; i++) {
            data_list.push(res.data[i]);
          }

          that.setData({
            pageData: data_list, //分页数据
            hideBottom: true
          });
          console.log(that.data.pageData);
        } else {
          //没有更多了
          that.setData({
            loadMoreText: "没有更多数据了", //分页数据
            hideBottom: false,
            pageIndex: that.data.pageIndex - 1
          });
        }
      });
  },
  //位置点击事件  
  listqy: function (e) {
    if (this.data.qyopen) {
      this.setData({
        qyopen: false,
        qyshow: false,
        nzopen: false,
        pxopen: false,
        nzshow: true,
        pxshow: true,
        shownavindex: 0
      })
    } else {
      this.setData({
        qyopen: true,
        qyshow: false,
        pxopen: false,
        nzopen: false,
        nzshow: true,
        pxshow: true,
        shownavindex: e.currentTarget.dataset.nav
      })
    }

  },
  listCategory: function (e) {
    var that = this;
    nav.navigateTo("../category/category?callBackPage=index");
  },
  listpx: function (e) {
    if (this.data.pxopen) {
      this.setData({
        nzopen: false,
        pxopen: false,
        qyopen: false,
        nzshow: true,
        pxshow: false,
        qyshow: true,
        shownavindex: 0
      })
    } else {
      this.setData({
        nzopen: false,
        pxopen: true,
        qyopen: false,
        nzshow: true,
        pxshow: false,
        qyshow: true,
        shownavindex: e.currentTarget.dataset.nav
      })
    }
  },
  //选择全国
  selectAllProvice: function (e) {
    var that = this;
    that.setData({
      selected_provice: 0,
      selected_city: 0,
      selected_region: 0,
      currentArea: '全国',
      city: {}
    });
    that.listqy();
    that.onSearch();
  },
  //选择全市
  selectAllCity: function (e) {
    var that = this;
    that.setData({
      selected_city: 0,
      selected_region: 0,
      currentArea: that.data.pname,
      region: {}
    });
    that.listqy();
    that.onSearch();
  },
  //选择全区
  selectAllArea: function (e) {
    var that = this;
    that.setData({
      selected_region: 0,
      currentArea: that.data.cname
    });
    that.listqy();
    that.onSearch();
  },
  //省份点击事件
  selectProvice: function (e) {
    console.log(e.currentTarget.dataset.city)
    var that = this;
    that.setData({
      selected_provice: e.currentTarget.dataset.city,
      selected_city: 0,
      selected_region: 0,
      pname: e.currentTarget.dataset.pname
    });
    //发起网络请求
    http.post(appConfig.baseUrl + 'Notice/GetRegionByParentId', {
        ParentId: e.currentTarget.dataset.city
      },
      function (res) { //
        console.log(res.data);
        that.setData({
          city: res.data,
          region: {}, //行政区列表
          //address: {} //行政区下属区域列表
        });
      },
      function (res) {
        console.log(res);
      });

  },
  //市选择事件
  selectCity: function (e) {
    var that = this;
    that.setData({
      selected_city: e.currentTarget.dataset.city,
      selected_region: 0,
      cname: e.currentTarget.dataset.cname
    });
    //发起网络请求
    http.post(appConfig.baseUrl + 'Notice/GetRegionByParentId', {
        ParentId: e.currentTarget.dataset.city
      },
      function (res) { //
        console.log(res.data);
        that.setData({
          region: res.data,
          //address: {} //行政区下属区域列表
        });
      },
      function (res) {
        console.log(res);
      });
  },
  //行政区选择事件
  selectRegion: function (e) {
    var that = this;
    that.setData({
      selected_region: e.currentTarget.dataset.city,
      currentArea: e.currentTarget.dataset.cname
    });
    that.listqy();
    that.onSearch();
  },
  selectcmditem: function (e) {
    var that = this;
    console.log(e.target.dataset.commander);
    var commander = e.target.dataset.commander
    that.setData({
      selected_publishTime: commander == that.data.selected_publishTime ? '' : commander
    })
  },
  selectstatus: function (e) {
    var that = this;
    console.log(e.target.dataset.status);
    console.log(that.data.selected_status)
    var status = e.target.dataset.status
    that.setData({
      selected_status: status == that.data.selected_status ? '' : status
    })
  },
  selectgender: function (e) {
    var that = this;
    console.log(e.target.dataset.gender);
    var gender = e.target.dataset.gender
    that.setData({
      selected_gender: gender == that.data.selected_gender ? -1 : gender
    })
  },
  selectcolor: function (e) {
    var that = this;
    console.log(e.target.dataset.color);
    console.log(that.data.selected_color)
    var color = e.target.dataset.color
    that.setData({
      selected_color: color == that.data.selected_color ? -1 : color
    })
  },
  //发布按钮点击事件
  gotopublish: function (e) {
    this.setData({
      hiddenModal: false
    });
  },
  //模态框关闭按钮点击事件
  modalCloseClick: function (e) {
    this.setData({
      hiddenModal: true
    });
  },
  //发布确认按钮点击事件
  onPublishClick: function (e) {
    console.log(e.target.dataset.noticeTypeId);
    //var noticeType = e.target.dataset.noticeTypeId;
    this.setData({
      nzopen: false,
      pxopen: false,
      qyopen: false,
      nzshow: true,
      pxshow: false,
      qyshow: true,
      shownavindex: 0,
      //hiddenModal: true 
    });
    tip.showToast('跳转中...', 'none');
    nav.navigateTo('../notice/notice', {
      noticeType: e.target.dataset.noticeTypeId
    });

  },
  gotoNoticeIndex: function (e) {
    var that = this;
    //wx.reLaunch({ url:'../index/index?noticeType=0'});
    that.setData({
      qyopen: false,
      qyshow: true,
      nzopen: false,
      pxopen: false,
      nzshow: true,
      pxshow: true,
      shownavindex: 0,
      noticeType: 0,
      navData: [{
        name: "寻宠", //文本
        current: 1, //是否是当前页，0不是  1是
        style: 0, //样式
        ico: 'icon-zhonglixunta', //不同图标
        fn: 'gotoNoticeIndex' //对应处理函数
      }, {
        name: "寻主人",
        current: 0,
        style: 0,
        ico: 'icon-xunren',
        fn: 'gotoPickupIndex'
      }, {
        name: "",
        current: 0,
        style: 1,
        ico: '',
        fn: 'gotopublish'
      }, {
        name: "圈子",
        current: 0,
        style: 0,
        ico: 'icon-qz',
        fn: 'gotoQuanzi',
      }, {
        name: "我的",
        current: 0,
        style: 0,
        ico: 'icon-wode2',
        fn: 'bindViewMy'
      }]
    });
    wx.setNavigationBarTitle({
      title: '寻宠'
    });
    that.bindResetClick();
    that.onSearch();
  },
  gotoPickupIndex: function (e) {
    var that = this;
    //wx.reLaunch({ url: '../index/index?noticeType=1' });
    that.setData({
      qyopen: false,
      qyshow: true,
      nzopen: false,
      pxopen: false,
      nzshow: true,
      pxshow: true,
      shownavindex: 0,
      noticeType: 1,
      navData: [{
        name: "寻宠", //文本
        current: 0, //是否是当前页，0不是  1是
        style: 0, //样式
        ico: 'icon-zhonglixunta', //不同图标
        fn: 'gotoNoticeIndex' //对应处理函数
      }, {
        name: "寻主人",
        current: 1,
        style: 0,
        ico: 'icon-xunren',
        fn: 'gotoPickupIndex'
      }, {
        name: "",
        current: 0,
        style: 1,
        ico: '',
        fn: 'gotopublish'
      }, {
        name: "圈子",
        current: 0,
        style: 0,
        ico: 'icon-qz',
        fn: 'gotoQuanzi',
      }, {
        name: "我的",
        current: 0,
        style: 0,
        ico: 'icon-wode2',
        fn: 'bindViewMy'
      }]
    });
    wx.setNavigationBarTitle({
      title: '寻主人'
    });
    that.bindResetClick();
    that.onSearch();
  },
  gotoQuanzi: function (e) {
    var that = this;
    nav.navigateTo("../quanzi/list/list");

  },
  bindViewMy: function (e) {
    nav.navigateTo("../mine/mine");
  },
  onSearch: function (e) {
    var that = this;
    console.log(that.data.noticeType)
    wx.showLoading({
      title: '玩命加载中...',
    });
    http.post(appConfig.baseUrl + 'Notice/QueryNoticeList', {
        PageIndex: 1,
        NoticeType: that.data.noticeType,
        ProviceId: that.data.selected_provice,
        CityId: that.data.selected_city,
        AreaId: that.data.selected_region,
        PublishTime: that.data.selected_publishTime,
        //RegionId: that.data.selected_address,
        Gender: that.data.selected_gender,
        CategoryId: that.data.selected_categoryChild,
        Color: that.data.selected_color
      },
      function (res) { //
        console.log(res.data);
        wx.hideLoading(); //关闭加载动画
        var result = that.calculateDistance(res.data);
        console.log(result);
        that.setData({
          pageIndex: 1, //当前页码
          pageData: res.data, //分页数据
          hideBottom: true,
          loadMoreText: '正在载入更多...'
        });

      },
      function (res) {
        console.log(res);
        wx.hideLoading(); //关闭加载动画
      });
  },
  bindResetClick: function (e) {
    var that = this;
    that.setData({
      selected_gender: -1,
      selected_color: -1,
      selected_status: '',
      selected_publishTime: ''
    });
  },
  bindSubmitClick: function (e) {
    var that = this;
    that.onSearch();
    that.setData({
      qyopen: false,
      qyshow: true,
      nzopen: false,
      pxopen: false,
      nzshow: true,
      pxshow: true,
      shownavindex: ''
    });
  },
  //距离计算
  calculateDistance: function (data) {
    var that = this;
    var result = data;
    var distance = 0;
    for (var i = 0; i < data.length; i++) {
      distance = util.getDistance(app.globalData.locationInfo.latitude, app.globalData.locationInfo.longitude, data[i].Latitude, data[i].Longitude);
      result[i].distance = distance;
    }
    return result;
  },
  /**
   * 重新定位
   */
  bindRefreshClick: function (e) {
    var that = this;
    var qqMap = new QQMapWX({
      key: appConfig.QQMapWXKey // 必填
    });
    app.getLocationInfo(function (data) {
      // 调用腾讯地图的接口查询当前位置
      qqMap.reverseGeocoder({
        location: {
          latitude: data.latitude,
          longitude: data.longitude
        },
        success: function (res) {
          console.log(res)

          that.setData({
            currentAddress: res.result.address_component.province + "-" + res.result.address_component.city + "-" + res.result.address_component.district,
            currentArea: res.result.address_component.district,
            pname: res.result.address_component.province,
            cname: res.result.address_component.city
          });
          //加载列表
          http.post(appConfig.baseUrl + 'Notice/GetCurrentRegion', {

              ProviceName: res.result.address_component.province,
              CityName: res.result.address_component.city,
              AreaName: res.result.address_component.district
            },
            function (res) { //
              console.log(res.data)
              if (res.data.Flag) {
                that.setData({
                  selected_provice: res.data.Content.split(",")[0],
                  selected_city: res.data.Content.split(",")[1],
                  selected_region: res.data.Content.split(",")[2]
                });
                //加载省列表
                http.post(
                  appConfig.baseUrl + 'Notice/GetRegionByParentId', {
                    ParentId: 1
                  },
                  function (res) {
                    that.setData({
                      provice: res.data
                    })
                  });
                //加载市列表
                http.post(
                  appConfig.baseUrl + 'Notice/GetRegionByParentId', {
                    ParentId: res.data.Content.split(",")[0]
                  },
                  function (res) {
                    that.setData({
                      city: res.data
                    })
                  });
                //加载区列表
                http.post(
                  appConfig.baseUrl + 'Notice/GetRegionByParentId', {
                    ParentId: res.data.Content.split(",")[1]
                  },
                  function (res) {
                    that.setData({
                      region: res.data
                    })
                  });
                //加载区列表

                http.post(appConfig.baseUrl + 'Notice/QueryNoticeList', {
                    PageIndex: 1,
                    ProviceId: that.data.selected_provice,
                    CityId: that.data.selected_city,
                    AreaId: that.data.selected_region,
                    CategoryId: that.data.selected_categoryChild,
                    NoticeType: that.data.noticeType
                  },
                  function (res) { //
                    console.log(res.data);
                    var result = that.calculateDistance(res.data);
                    wx.hideLoading(); //关闭加载动画
                    that.setData({
                      pageIndex: 1, //当前页码
                      pageData: res.data, //分页数据
                      hideBottom: true,
                      loadMoreText: '正在载入更多...'
                    });

                  });
              }
            });
          //获取数据更新页面
          that.listqy();
          //that.onSearch();
        },
        fail: function (res) {
          console.log(res);
        },
        complete: function (res) {
          // console.log(res);
        }
      });
    });
  },
  /**
   * 附近地图
   */
  bindMapClick: function (e) {
    nav.navigateTo("../position/position");
  },
  /**
   * 蒙层点击
   */
  bindMaskClick: function (e) {
    console.log('点击了蒙层');
  },
  /**
   * 控制 pop 的打开关闭
   * 该方法作用有2:
   * 1：点击弹窗以外的位置可消失弹窗
   * 2：用到弹出或者关闭弹窗的业务逻辑时都可调用
   */
  toggleDialog() {
    this.setData({
      hiddenModal: !this.data.hiddenModal
    });

  },
  preventTouchMove: function () {
    console.log('123');
    return;
  }
})